from loguru import logger
import sys
import asyncio
from utils.enums import FilePath


class Log:
    def __init__(self, log_file=FilePath.LOGS_PATH.value + 'app.log', level="INFO", rotation="500 MB",
                 retention="10 days", compression="zip"):
        self.log_file = log_file
        self.level = level
        self.rotation = rotation
        self.retention = retention
        self.compression = compression
        self._configure_logger()

    def _configure_logger(self):
        logger.remove()  # 移除默认的 logger
        logger.add(sys.stdout, format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}", level=self.level,
                   enqueue=True)
        logger.add(self.log_file, format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}", rotation=self.rotation,
                   retention=self.retention, compression=self.compression, enqueue=True)

        # sys.excepthook = self._log_exception  # 捕获全局异常

    @staticmethod
    def _log_exception(exc_type, exc_value, exc_traceback):
        if issubclass(exc_type, KeyboardInterrupt):
            sys.__excepthook__(exc_type, exc_value, exc_traceback)
            return
        logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))

    @staticmethod
    def info(message):
        logger.info(message)

    @staticmethod
    def debug(message):
        logger.debug(message)

    @staticmethod
    def warning(message):
        logger.warning(message)

    @staticmethod
    def error(message):
        logger.error(message)

    @staticmethod
    def critical(message):
        logger.critical(message)

    @staticmethod
    async def async_log(messages):
        for message in messages:
            logger.info(message)
            await asyncio.sleep(0.01)

#
# # 使用示例
# if __name__ == "__main__":
#     loguru_logger = Log()
#
#     loguru_logger.info("This is an info message")
#     loguru_logger.debug("This is a debug message")
#     loguru_logger.warning("This is a warning message")
#     loguru_logger.error("This is an error message")
#     loguru_logger.critical("This is a critical message")
#
#     try:
#         1 / 0
#     except ZeroDivisionError:
#         loguru_logger.error("An error occurred")
#
#     asyncio.run(loguru_logger.async_log([f"Async log message {i}" for i in range(100)]))
#     loguru_logger.info("Program continues to run...")
